<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useUserStore } from '@/store/user';
import { showDialog, showToast } from 'vant';
import { router } from '@/router';
import { deleteCourse, getCourseListByUserId } from '@/api/classroom';

const isManageMode = ref(false);
const showTeacher = ref(false);
const list = ref([] as any[]); 
const loading = ref(false); 
const finished = ref(false); 
const isLoading = ref(false);
const searchKeyword = ref('');

const userStore = useUserStore();
const userId = userStore.user.id || ''; // 获取用户ID

onMounted(() => {
    checkRole();
    fetchCourseList(); // 组件挂载时请求课程列表数据
})

const back = () => {
    console.log("我要准备返回了嘛？")
    router.push('/home');
}

const checkRole = () => {
    const userStore = useUserStore();
    let userRoleCode = userStore.getRoleCode;
    if (userRoleCode == 'TEACHER') {
        showTeacher.value = true;
    } else {
        showTeacher.value = false;
    }
}

const filteredList = computed(() => {
    if (!searchKeyword.value) {
        return list.value; 
    }
    return list.value.filter((item) =>
        item.title.includes(searchKeyword.value)
    );
});

// 请求课程列表数据
const fetchCourseList = async () => {
    loading.value = true;
    try {
        const res = await getCourseListByUserId(userId);
        if (res.code === 200) {
            list.value = res.data || [];
            finished.value = true;
        }else if (res.code === 420) {
            showToast('当前没有课程哦');
        } else {
            showToast(res.msg || '获取课程失败');
        }
    } catch (error) {
        showToast('请求失败');
    } finally {
        loading.value = false;
    }
}
const onRefresh = async () => {
    await fetchCourseList();
    isLoading.value = false;
    showToast('刷新成功');
}

const handleDelete = (courseId: string) => {
  showDialog({
    title: '确认删除',
    message: '确定要删除这门课程吗？',
    showCancelButton: true
  })
  .then(() => {
    // 确认删除
    deleteCourse(courseId).then(() => {
      showToast('删除成功');
      // 重新加载课程列表
      fetchCourseList();
    }).catch((err) => {
      console.error('删除失败:', err);
      showToast('删除失败，请重试');
    });
  })
  .catch(() => {
    // 取消删除，不做任何操作
  });
};

const toggleManageMode = () => {
    // 切换管理模式
    isManageMode.value = !isManageMode.value;
};

const enterClassroom = (item: any) => {
    showToast(`进入课堂：${item.name}`);
    router.push({ name: 'course', query: { t: item.name, d: item.description, courseId: item.id, userId } })
};

// 搜索事件
const onSearch = () => {
    showToast(`搜索关键词：${searchKeyword.value}`);
};

// 取消搜索事件
const onCancel = () => {
    searchKeyword.value = ''; // 清空搜索关键词
    showToast('已取消搜索');
};
const creatCourses = () => {
    router.push('/coursecreate'); 
};
defineExpose({
    list,
    searchKeyword,
    filteredList,
    loading,
    finished,
    isLoading,
    onRefresh,
    enterClassroom,
    onSearch,
    onCancel,
});
</script>

<template>
    <div class="container">
        <!-- <YHeader></YHeader> -->
        <div class="container-icon">
        <div class="icon">
            <van-icon @click="back" name="arrow-left" size="32" />
        </div>
        <div class="manage-course">
                <van-button 
                type="primary" 
                size="small" 
                class="white-button" 
                @click="toggleManageMode">{{ isManageMode ? '退出管理' : '管理课程' }}</van-button>
            </div>
            <div class="creat-course">
                <van-button type="primary" size="small" class="white-button" @click="creatCourses">创建课程</van-button>
            </div>
    </div>
        <div class="list-container">
            <!-- 搜索框 -->
            <!-- <van-search v-model="searchKeyword" placeholder="请输入课堂名称" show-action @search="onSearch"
                @cancel="onCancel" /> -->
            <div class="classroom-list">
                <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
                    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                        <van-cell v-for="(item, index) in filteredList" :key="index" :title="item.name"
                            :label="item.description" icon="fire-o">
                            <template #icon>
                                <van-image width="50" height="50" :src="item.coverImage" fit="cover" round />
                            </template>
                            <template #extra>
                                  <van-button 
                                  v-if="!isManageMode"
                                  type="primary" 
                                  size="small" 
                                  @click="enterClassroom(item)">
                                      进入课程
                                    </van-button>
                                  <van-button
                                   v-else
                                   type="danger"
                                  size="small"
                                  @click="handleDelete(item.id)">
                                     删除课程
                                 </van-button>
                             </template>
                        </van-cell>
                    </van-list>
                </van-pull-refresh>
            </div>
        </div>
    </div>

</template>

<style lang="scss" scoped>
.list-container {
    height: 80%;
    padding: 5px;
}

.classroom-list {
    height: calc(100vh - 80px);
    /* 减去顶部导航栏高度 */
    overflow: auto;
    /* 允许滚动 */
}

.van-cell {
    align-items: center;
}

.van-image {
    margin-right: 10px;
}
.manage-course {
    position: absolute;
    top: 1px;
    right: 20px;
}
.creat-course {
    position: absolute;
    top: 1px;
    right: 90px;
}


.white-button {
    background-color: #fff;
    border: 1px solid #ddd;  
    color: #007aff;  
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); 
}

.white-button:hover {
    background-color: #f2f2f2;  
    border-color: #bbb; 
}
</style>